<template>
  <div v-if="visible">
    <el-dialog
      v-model="show"
      :title="title" :close-on-press-escape="false" :close-on-click-modal="false"
      :show-close="false">
      <el-form ref="formRef" :model="deptInfo" :rules="rules" label-width="80px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="deptInfo.departmentName" placeholder="请输入部门名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input v-model="deptInfo.departmentDesc" type="textarea" placeholder="请输入部门描述" clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">关闭</el-button>
        <el-button type="primary" @click="save('form')">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, toRefs, onBeforeMount } from 'vue'
import { propsConst } from '@/utils/propsConstant'
import { post } from '@/utils/httpRequest'
import { ElMessage } from 'element-plus'
import { addDepartmentUrl, updateDepartmentByIdUrl } from '@/api/api'

export default {
  name: 'departmentInfo',
  setup (props, { emit }) {
    console.log(props)
    const {
      type,
      info,
      parentId
    } = toRefs(props)
    const show = ref(true)
    const cancel = () => {
      emit('update:visible', false)
    }
    const formRef = ref(null)
    // 验证规则
    const rules = reactive({
      departmentName: [
        {
          required: true,
          message: '请输入部门名称',
          trigger: 'blur'
        }
      ]
    })
    const save = () => {
      formRef.value.validate().then(async () => {
        let result
        if (type.value === 0 || type.value === 4) {
          result = await post(addDepartmentUrl, deptInfo.value)
        } else if (type.value === 1) {
          result = await post(updateDepartmentByIdUrl, deptInfo.value)
        }
        if (result.code === 200) {
          ElMessage.success(result.message)
          emit('save')
          emit('update:visible', false)
        }
      }).catch(() => {
        console.log('lose info...')
      })
    }
    const deptInfo = ref({
      departmentDesc: null,
      departmentName: null,
      departmentParentId: 0
    })
    onBeforeMount(() => {
      if (type.value === 1) {
        deptInfo.value = info.value
      } else if (type.value === 4) {
        deptInfo.value.departmentParentId = parentId.value
      }
    })
    return {
      formRef,
      rules,
      deptInfo,
      show,
      cancel,
      save
    }
  },
  props: Object.assign(propsConst, {
    title: {
      type: String,
      required: false,
      default: '部门详情'
    },
    info: {
      type: Object,
      required: false,
      default () {
        return {}
      }
    },
    parentId: {
      type: Number,
      required: false,
      default: 0
    }
  })
}
</script>

<style scoped>

</style>
